package com.lagou.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lagou.common.RequestPage;
import com.lagou.dao.UserDao;
import com.lagou.entity.LagouUser;
import com.lagou.feign.CodeServiceFeignClient;
import com.lagou.service.UserService;
import com.lagou.util.JwtTool;
import com.lagou.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private CodeServiceFeignClient codeServiceFeignClient;
    @Autowired
    private UserDao userDao;
    @Value("${issuer}")
    String issuer;
    @Value("${secret-key}")
    String secret;

    @Override
    public Boolean register(String email, String password, String code) {

        LagouUser user = userDao.getUserByEmail(email);

        if (null != user) {
            log.warn("该用户已注册: {}", email);
            throw new RuntimeException(String.format("该用户已注册: %s", email));
        }

        // 验证码校验(0正确 1错误 2超时)
        Integer validCode = codeServiceFeignClient.validateCode(email, code).getData();
        if (validCode == 0) {
            return userDao.insert(LagouUser.builder().email(email).password(MD5Util.MD5_16(password)).build()) > 0;
        }

        log.error("验证码{}", validCode == 1 ? "错误" : "过期");
        throw new RuntimeException(String.format("验证码%s", validCode == 1 ? "错误" : "过期"));
    }

    @Override
    public Boolean isRegistered(String email) {
        return userDao.getUserByEmail(email) != null;
    }

    @Override
    public String login(String email, String password) {
        LagouUser user = userDao.getUserByEmail(email);
        if (null == user) {
            throw new RuntimeException(String.format("%s 用户不存在", email));
        }

        if (!MD5Util.MD5_16(password).equalsIgnoreCase(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 签发JWT Token
        String jwt;
        try {
            jwt = JwtTool.generateJwt(email, issuer, secret);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jwt;
    }

    @Override
    public String getEmail(String token) {
        DecodedJWT decodedJWT = JwtTool.parseJwtToken(token, secret);
        if (null == decodedJWT) {
            throw new RuntimeException("token无效");
        }
        return decodedJWT.getSubject();
    }

    @Override
    public PageInfo<LagouUser> getUserList(RequestPage<Object> requestPage) {
        PageHelper.startPage(requestPage.getPageNum(), requestPage.getPageSize());
        List<LagouUser> list = userDao.getAllList();
        PageInfo<LagouUser> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }
}
